<template>
  <div class="chat-container">
    <!-- 消息展示区域 -->
    <div ref="messagesContainer" class="messages">
      <div v-for="(message, index) in messages" :key="index" class="message">
        <!-- 用户消息 -->
        <div v-if="message.role === 'user'" class="user-message">
          <div class="bubble">
            <div class="content">{{ message.content }}</div>
          </div>
          <div class="avatar">
            <span>👤</span>
          </div>
        </div>

        <!-- AI消息（支持流式显示） -->
        <div v-else class="ai-message">
          <div class="avatar">
            <span>🤖</span>
          </div>
          <div class="bubble">
            <div class="content">
              <!-- <span v-for="(chunk, i) in message.chunks" :key="i">{{ chunk }}</span> -->
              <div v-html="renderMarkdown(message.content)"></div>
              <span v-if="message.loading" class="cursor">▎</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
      <!-- 输入区域 -->
    <div class="input-area">
      <textarea
        v-model="inputText"
        placeholder="输入你的观点..."
        @keydown.enter.exact.prevent="sendMessage"
      ></textarea>
      <button 
        :disabled="isLoading || !inputText.trim()" 
        @click="sendMessage"
      >
        {{ isLoading ? '生成中...' : '发送' }}
      </button>
      <button 
        @click="openDebateDialog">开始辩论</button>
    </div>
        <!-- 辩论设置对话框 -->
     <div v-if="showDebateDialog" class="dialog-overlay">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>创建辩论</h3>
          <button class="close-btn" @click="closeDebateDialog">×</button>
        </div>
        <div class="dialog-content">
          <div class="form-group">
            <label>辩题</label>
            <input 
              type="text" 
              v-model="debateTopic" 
              placeholder="请输入您的辩题"
              required
            />
          </div>
          <div class="form-group">
            <label>辩论立场</label>
            <div class="position-options">
              <label class="option">
                <input type="radio" value="pro" v-model="debatePosition" name="position" />
                <span>正方</span>
              </label>
              <label class="option">
                <input type="radio" value="con" v-model="debatePosition" name="position" />
                <span>反方</span>
              </label>
            </div>
          </div>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="closeDebateDialog">取消</button>
          <button 
            class="confirm-btn" 
            :disabled="!debateTopic || !debatePosition"
            @click="beginDebate"
          >
            开始辩论
          </button>
        </div>
      </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import type { WebSocketMessage } from '../models/general'
import { marked } from 'marked'
import { getUser } from '../services/userServ'
import { createSession } from '../services/debateServ'

import router from '../router/index'
import { success } from '../tools/messageBox'


interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  chunks: string[] // 流式块
  loading?: boolean
  completed?: boolean
}

const messages = ref<ChatMessage[]>([])
const inputText = ref('')
const isLoading = ref(false)
let user_id = ''
let session_id = ''
const messagesContainer = ref<HTMLElement | null>(null)
let socket: WebSocket | null = null
let inThinkBlock = false

const isDebateStarted = ref(false)
const showDebateDialog = ref(false)
const debateTopic = ref('')
const debatePosition = ref('pro') 


//AI生成文字格式渲染
const renderMarkdown = (content: string) => {
  return marked.parse(content)
}

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 初始化WebSocket连接
const initWebSocket = async() => {
  const res = await getUser();
  if (!res) {
    alert("未登录或 token 无效");
    router.push('/Login')
  }

  socket = new WebSocket(`ws://localhost:8000/api/chat/stream/${session_id}`)

  socket.onmessage = (event) => {
    const data: WebSocketMessage = JSON.parse(event.data)
    
    // 查找当前进行中的消息
    const lastMessage = messages.value[messages.value.length - 1]
    
    if (data.type === 'start') {
      messages.value.push({
        role: 'assistant',
        content: '',
        chunks: [],
        loading: true
      })
    }
    // else if (data.type === 'stream' && lastMessage?.loading) {
    //   lastMessage.chunks.push(data.content)
    //   lastMessage.content = lastMessage.chunks.join('')
    //   scrollToBottom()
    // }
    else if (data.type === 'stream' && lastMessage?.loading) {
      let token = data.content

      // 检测 <think> 标签开始
      if (token.includes('<think')) {
        inThinkBlock = true
      }

      // 如果不在 think block 内则显示
      if (!inThinkBlock) {
        lastMessage.chunks.push(token)
        lastMessage.content = lastMessage.chunks.join('')
        scrollToBottom()
      }

      // 检测 </think> 标签结束
      if (token.includes('</think>')) {
        inThinkBlock = false
      }
    }

        else if (data.type === 'end') {
          if (lastMessage) {
            lastMessage.loading = false
            lastMessage.completed = true
          }
          isLoading.value = false
        }
    else if (data.type === 'error') {
      console.error('Error:', data.content)
      messages.value.push({
        role: 'assistant',
        content: `错误: ${data.content}`,
        chunks: [],
        completed: true
      })
      isLoading.value = false
    }
  }

  socket.onclose = () => {
    console.log('WebSocket连接关闭')
    isLoading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if(!isDebateStarted.value) {
    alert("请先创建辩论")
    return
  }
  if (!inputText.value.trim() || isLoading.value) return

  const userMessage: ChatMessage = {
    role: 'user',
    content: inputText.value.trim(),
    chunks: [inputText.value.trim()]
  }
  
  messages.value.push(userMessage)
  inputText.value = ''
  isLoading.value = true
  
  try {
    socket?.send(JSON.stringify({
      message: userMessage.content
    }))
    
    scrollToBottom()
  } catch (err) {
    console.error('发送失败:', err)
    isLoading.value = false
  }
}

// 打开辩论设置对话框
const openDebateDialog = () => {
  showDebateDialog.value = true
}

// 关闭辩论设置对话框
const closeDebateDialog = () => {
  showDebateDialog.value = false
  debateTopic.value = ''
  debatePosition.value = 'pro'
}


const beginDebate = async () => {
  try {
    const postData = {
      topic: debateTopic.value,
      position: debatePosition.value,
      result: ''
    };
    const res = await createSession(postData)
    console.log(res)

    if (res) {
      session_id = res.id
      success("新会话创建成功!")
      isDebateStarted.value = true
      showDebateDialog.value = false

      // 初始化 WebSocket
      initWebSocket()
    } else {
      alert("会话创建失败")
    }
  } catch (err) {
    console.error("创建会话失败:", err)
    alert("创建会话失败")
  }
}

// 生命周期
onMounted(initWebSocket)
onBeforeUnmount(() => {
  socket?.close()
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  width: 1000px;
  height: 100%;
  background: #f9f9fb;
  min-width: 0;
  min-height: 0;
}

.messages {
  flex: 1 1 0%;
  overflow-y: auto;
  width: 100%;
  max-width: 100%;
  min-width: 0;
  margin: 0;
  box-sizing: border-box;
}

/* 消息气泡样式 */
.user-message,
.ai-message {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 1.25rem;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.bubble {
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  max-width: 70%;
  font-size: 1rem;
  line-height: 1.5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  word-break: break-word;
  transition: all 0.2s ease;
}

.user-message .bubble {
  background-color: #d1f3d3;
}

.ai-message .bubble {
  background-color: #ffffff;
  border: 1px solid #e0e0f0;
  text-align: left;

}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #ffffff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
}

/* 输入区域美化 */
.input-area {
  padding: 1rem 1.5rem;
  display: flex;
  gap: 0.75rem;
  align-items: flex-end;
  border-top: 1px solid #eee;
  background-color: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
}

textarea {
  flex: 1;
  min-height: 3.2rem;
  max-height: 6rem;
  padding: 0.75rem 1rem;
  font-size: 1rem;
  border-radius: 0.75rem;
  border: 1px solid #ddd;
  resize: none;
  transition: border-color 0.3s ease;
}

textarea:focus {
  outline: none;
  border-color: #007bff;
}

button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 0.75rem;
  font-weight: 500;
  font-size: 1rem;
  background: linear-gradient(to right, #007bff, #0062cc);
  color: white;
  transition: transform 0.2s ease, opacity 0.2s ease;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

button:not(:disabled):hover {
  transform: scale(1.02);
}

.cursor {
  color: #007bff;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .messages {
    padding: 1rem;
  }

  .bubble {
    max-width: 90%;
  }

  .input-area {
    flex-direction: column;
    align-items: stretch;
  }

  textarea {
    width: 100%;
  }

  button {
    width: 100%;
  }
}
/* 新增对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 500px;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
}

.close-btn {
  border: none;
  background: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0 8px;
}

.close-btn:hover {
  color: #333;
}

.dialog-content {
  padding: 20px 24px;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #444;
  font-weight: 500;
}

.form-group input[type="text"] {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
}

.form-group input[type="text"]:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
}

.position-options {
  display: flex;
  gap: 1rem;
  margin-top: 8px;
}

.option {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.option input[type="radio"] {
  accent-color: #007bff;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: #007bff;
  color: white;
}

button {
  padding: 8px 20px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
}

button:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}
</style>
